<template>
  <div class="box" ref="targetElement">
    <div class="search-box" ref="searchBox">
      <div class="search-top-box">
        <div class="search-top-left-box">
          <el-form ref="div" :inline="true" :model="formSearch" label-width="110px">
            <el-form-item label="项目名称">
              <el-select filterable @change="onSearch(1)" clearable class="form-width" v-model="formSearch.project_id"
                placeholder="选择项目名称">
                <el-option v-for="item in searchProjectList" :key="item.id" :label="item.project_name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="项目品牌">
              <el-select filterable @change="onSearch(1)" clearable class="form-width" v-model="formSearch.brand_id"
                placeholder="选择项目品牌">
                <el-option v-for="item in brandList" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="项目类型">
              <el-select filterable @change="onSearch(1)" clearable class="form-width"
                v-model="formSearch.store_type_id" placeholder="选择项目类型">
                <el-option v-for="item in storeTypeList" :key="item.id" :label="item.store_type_name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="签约主体">
              <el-select filterable @change="onSearch(1)" clearable class="form-width"
                v-model="formSearch.signing_company_id" placeholder="选择签约主体">
                <el-option v-for="item in companyList" :key="item.id" :label="item.account_name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <template v-if="moreSearchShow">
              <el-form-item label="项目编号">
                <el-input @change="onSearch(1)" clearable class="form-width" v-model="formSearch.project_number"
                  placeholder="输入项目编号"></el-input>
              </el-form-item>
              <el-form-item label="合同编号">
                <el-input @change="onSearch(1)" clearable class="form-width" v-model="formSearch.contract_number"
                  placeholder="输入合同编号"></el-input>
              </el-form-item>
            </template>
            <!-- 装修合同 -->
            <template v-if="(activeName == 1 || activeName == 3) && moreSearchShow">
              <el-form-item label="合同开工日期">
                <el-date-picker value-format="yyyy-MM-dd" @change="onSearch(1)" class="form-width"
                  v-model="formSearch.contract_commencement_date" type="daterange" range-separator="至"
                  start-placeholder="开始日期" end-placeholder="结束日期">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="合同完工日期">
                <el-date-picker value-format="yyyy-MM-dd" @change="onSearch(1)" class="form-width"
                  v-model="formSearch.contract_completion_date" type="daterange" range-separator="至"
                  start-placeholder="开始日期" end-placeholder="结束日期">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="合同工期">
                <el-input v-input-limit="0" @change="onSearch(1)" clearable class="form-width"
                  v-model="formSearch.contract_duration_days" placeholder="输入合同工期"></el-input>
              </el-form-item>
            </template>
            <template v-if="moreSearchShow">
              <el-form-item label="合同签约金额">
                <el-input v-input-limit="2" @change="onSearch(1)" clearable class="form-width"
                  v-model="formSearch.contract_price" placeholder="输入合同签约金额"></el-input>
              </el-form-item>
              <el-form-item label="创建时间">
                <el-date-picker value-format="yyyy-MM-dd" @change="onSearch(1)" class="form-width"
                  v-model="formSearch.contract_commencement_date" type="daterange" range-separator="至"
                  start-placeholder="开始日期" end-placeholder="结束日期">
                </el-date-picker>
              </el-form-item></template>
          </el-form>
        </div>
        <div class="search-top-right-box">
          <p @click="moreSearchFunc">
            {{ moreSearchShow ? "收起" : "展开"
            }}<i :class="moreSearchShow ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i>
          </p>
          <el-button type="primary" @click="onSearch">查询</el-button>
          <el-button type="primary" @click="addContractFunc"
            v-if="$isPer(permission, ['contract_add'])">新增合同</el-button>
        </div>
      </div>
    </div>
    <!-- table -->
    <div class="page-list" ref="pageList">
      <div class="list-top-box">
        <div class="tab-box">
          <el-tabs v-model="activeName" @tab-click="onSearch(1)">
            <el-tab-pane label="施工合同" name="1"></el-tab-pane>
            <el-tab-pane label="勘场合同" name="2"></el-tab-pane>
            <el-tab-pane label="增减项合同" name="3"></el-tab-pane>
            <el-tab-pane label="定金合同" name="4"></el-tab-pane>
          </el-tabs>
        </div>
        <div class="list-top-box-right">
          <p class="list-top-box-left">
            已选<span class="num">{{ multipleSelection.length }}</span>/{{ tableData.length }}数据
          </p>
          <el-button type="primary" @click="exportFunc" :disabled="tableData.length == 0"
            v-if="$isPer(permission, ['contract_exportContractExcel'])">
            导出合同列表
          </el-button>
          <el-button type="primary" @click="contractInvalidation"
            :disabled="multipleSelection.length != 1 || multipleSelection[0].contract_state == 2"
            v-if="$isPer(permission, ['contract_contractInvalidation'])">合同作废</el-button>
        </div>
      </div>
      <div class="table-box" v-loading="pageLoading">
        <el-table border ref="table" @row-click="handleHighlightChangeTable" highlight-selection-row :header-cell-style="{
          background: '#FAFBFC',
          color: '#828A9D',
          textAlign: 'center',
        }" :cell-style="{ textAlign: 'center', color: '#1B2431' }" :data="tableData"
          @selection-change="handleSelectionChange" height="100%">
          <el-table-column type="selection" width="80"></el-table-column>
          <el-table-column min-width="140px" prop="" fixed="left" label="ID">
            <template slot-scope="scope">
              <el-button v-if="$isPer(permission, ['contract_detail'])" type="text" @click="goToDetail(scope.row)">
                {{ $assemblyListNo('XMHT', scope.row.id) }}</el-button>
              <span v-else>
                {{ $assemblyListNo('XMHT', scope.row.id) }}</span>
            </template>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('ht_htlx')" min-width="100px" prop="contract_type" label="合同类型"
            show-overflow-tooltip>
            <template slot-scope="scope">
              <span v-if="scope.row.contract_type == 1">施工合同</span>
              <span v-if="scope.row.contract_type == 2">勘场合同</span>
              <span v-if="scope.row.contract_type == 3">增减项合同</span>
              <span v-if="scope.row.contract_type == 4">定金合同</span>
            </template>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('ht_qyzt')" min-width="180px" prop="account_name" label="签约主体"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('ht_xmmc')" min-width="180px" fixed="left" prop="project_name"
            label="项目名称" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.project_name || "--" }}
            </template>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('ht_xmbh')" min-width="130px" fixed="left" prop="project_number"
            label="项目编号" show-overflow-tooltip>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('ht_xmpp')" fixed="left" min-width="120px" prop="" label="项目品牌"
            show-overflow-tooltip>
            <template slot-scope="scope">
              <el-tag :color="`${scope.row.colour}`" style="color: #ffffff;">
                {{ scope.row.brand_name }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('ht_xmlx')" min-width="120px" prop="" label="项目类型"
            show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.store_type_name || "--" }}
            </template>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('ht_htbh')" min-width="160px" prop="contract_number" label="合同编号"
            show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.contract_number || "--" }}
            </template>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('ht_cjsj')" min-width="180px" prop="" label="合同签约日期"
            show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.created_at || "--" }}
            </template>
          </el-table-column>
          <el-table-column v-if="(activeName == 1 || activeName == 3) && $fieldShowFunc('ht_hekgrq')" min-width="120px"
            prop="" label="合同开工日期" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.contract_commencement_date || "--" }}
            </template>
          </el-table-column>
          <el-table-column v-if="(activeName == 1 || activeName == 3) && $fieldShowFunc('ht_hewgrq')" min-width="120px"
            prop="" label="合同完工日期" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.contract_completion_date || "--" }}
            </template>
          </el-table-column>
          <el-table-column v-if="(activeName == 1 || activeName == 3) && $fieldShowFunc('ht_htgq')" min-width="90px"
            prop="" label="合同工期" show-overflow-tooltip>
            <template slot-scope="scope">
              {{
                scope.row.contract_duration_days
                  ? scope.row.contract_duration_days + "天"
                  : "--"
              }}
            </template>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('ht_heqyje')" min-width="110px" prop="" label="合同签约金额"
            show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.contract_price ? scope.row.contract_price + "元" : "--" }}
            </template>
          </el-table-column>
          <el-table-column v-if="activeName == 1 && $fieldShowFunc('ht_sqkje')" min-width="110px" prop="" label="首期款金额"
            show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.down_payment ? scope.row.down_payment + "元" : "--" }}
            </template>
          </el-table-column>
          <el-table-column v-if="activeName == 1 && $fieldShowFunc('ht_jdkje')" min-width="110px" prop="" label="进度款金额"
            show-overflow-tooltip>
            <template slot-scope="scope">
              {{
                scope.row.progress_payment ? scope.row.progress_payment + "元" : "--"
              }}
            </template>
          </el-table-column>
          <el-table-column v-if="activeName == 1 && $fieldShowFunc('ht_wkje')" min-width="110px" prop="" label="尾款金额"
            show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.balance_payment ? scope.row.balance_payment + "元" : "--" }}
            </template>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('ht_cjsj')" min-width="180px" prop="" label="创建时间"
            show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.created_at || "--" }}
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页 -->
      <div class="page-footer">
        <el-pagination class="el-pagination" @current-change="handleCurrentChange" :current-page="page" :page-size="num"
          @size-change="handleSizeChange" layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>
    </div>
    <!-- 导出合同列表 -->
    <el-dialog :modal-append-to-body="false" title="导出合同字段选择" :visible.sync="exportVisible" width="680px"
      :before-close="exportCloseFunc">
      <el-checkbox class="checkbox-item" v-model="allChecked" @change="allCheckedChangeFunc">全选</el-checkbox>
      <div v-loading="exportLoading">
        <div class="export-scroll">
          <el-checkbox-group v-model="exportrVal">
            <el-checkbox class="checkbox-item" v-for="(item, index) in exportArr" :key="index" :label="item.label"
              border></el-checkbox>
          </el-checkbox-group>
        </div>
        <p v-if="exportUrl">导出文件链接：<el-button @click="$openUrlFunc(exportUrl[0])" type="text">{{
          exportUrl[1]
            }}</el-button></p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="exportSubmitFunc">提交</el-button>
        <el-button @click="exportCloseFunc">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import brandApi from "@/api/brandApi";
import storeTypeApi from "@/api/storeTypeApi";
import contractApi from "@/api/contractApi";
import commonApi from "@/api/common";
import { getUserInfo } from "@/utils/auth";
import companyApi from "@/api/companyApi";
import proContractApi from "@/api/proContractApi";
import { zxhtFieldArr, kchtFideldArr, zjxhtFideldArr, djhtFideldArr } from "@/utils/exportField";
export default {
  name: "contractManagement",
  data() {
    return {
      // 导出用户列表
      allChecked: false,//是否全选字段
      exportLoading: false,//导出loading
      exportVisible: false,//导出弹窗
      exportUrl: '',//导出url
      exportrVal: [],//导出勾选字段
      exportArr: [],//导出字段数组

      activeName: "1",
      userInfo: "",
      tableData: [],
      formSearch: {},
      moreSearchShow: false,
      page: 1,
      num: 10,
      total: 0,
      pageLoading: false,
      multipleSelection: [],
      companyList: [], //签约主体
      brandList: [], //品牌
      storeTypeList: [], //门店类型
      searchProjectList: [], //项目列表
      permission: [],//操作权限
    };
  },
  watch: {},
  computed: {},
  activated() { },
  destroyed() {
    window.removeEventListener('resize', this.handleResize);
    // 移除窗口大小变化事件监听器，防止内存泄漏
    if (this.resizeObserver) {
      // 停止观察目标元素，防止内存泄漏
      this.resizeObserver.disconnect();
    }
  },
  deactivated() {
    window.removeEventListener('resize', this.handleResize);
    // 移除窗口大小变化事件监听器，防止内存泄漏
    if (this.resizeObserver) {
      // 停止观察目标元素，防止内存泄漏
      this.resizeObserver.disconnect();
    }
  },
  activated() {
    // 监听窗口大小变化事件
    window.addEventListener('resize', this.handleResize);
    this.onSearch();
  },
  mounted() {
    this.handleResize();
    // 监听窗口大小变化事件
    window.addEventListener('resize', this.handleResize);
    // 操作权限
    this.$getHtmlAuthority(this.$route.path).then(res => {
      console.log(res, "getHtmlAuthority");
      this.permission = res.data.permission;
    })
    this.userInfo = getUserInfo();

    this.getContractList(); //合同列表
    this.getCompanyList(); //签约主体
    this.getBrandList(); //品牌
    this.getStoreTypeList(); //门店类型
    this.selectProjectList(); //项目列表
  },
  methods: {
    handleResize() {
      const target = this.$refs.targetElement;
      const searchBox = this.$refs.searchBox;
      const pageList = this.$refs.pageList;
      // 创建 ResizeObserver 实例
      const resizeObserver = new ResizeObserver(entries => {
        setTimeout(() => {
          console.log('元素变为:', searchBox.offsetHeight);
          // searchBox.offsetHeight + 'px'
          pageList.style.height = 'calc(100% - ' + (searchBox.offsetHeight + 15) + 'px)';
        }, 0);
      });
      // 开始观察目标元素
      resizeObserver.observe(target);

      // 存储 resizeObserver 实例，以便在组件销毁时停止观察
      this.resizeObserver = resizeObserver;
    },
    // 导出提交
    exportSubmitFunc() {
      let exportrVal = this.exportrVal;
      let exportArr = this.exportArr;
      let formSearch = this.formSearch;//列表筛选项
      if (!exportrVal.length) {
        this.$message({
          type: 'warning',
          message: "请勾选需要导出的字段"
        })
        return;
      }
      let field_list = [];//提交列表
      exportrVal.forEach(item => {
        let index = exportArr.findIndex(child => {
          return item == child.label;
        })
        if (index != -1) {
          field_list.push(exportArr[index].value);
        }
      })
      this.exportContractExcel({
        field_list,
        type: Number(this.activeName),
        signing_company_id: formSearch.signing_company_id || "",
        project_id: formSearch.project_id || "",
        project_number: formSearch.project_number || "",
        brand_id: formSearch.brand_id || "",
        store_type_id: formSearch.store_type_id || "",
        contract_number: formSearch.contract_number || "",
        customer_contact: formSearch.customer_contact || "",
        customer_phone: formSearch.customer_phone || "",
        increase_or_decrease: formSearch.increase_or_decrease || "",
        change_content: formSearch.change_content || "",
        construction_content: formSearch.construction_content || "",
        signatory_phone: formSearch.signatory_phone || "",
        signatory_name: formSearch.signatory_name || "",
        contract_commencement_date_start: formSearch.contract_commencement_date
          ? formSearch.contract_commencement_date[0]
          : "",
        contract_commencement_date_end: formSearch.contract_commencement_date
          ? formSearch.contract_commencement_date[1]
          : "",
        contract_completion_date_start: formSearch.contract_completion_date
          ? formSearch.contract_completion_date[0]
          : "",
        contract_completion_date_end: formSearch.contract_completion_date
          ? formSearch.contract_completion_date[1]
          : "",
        contract_duration_days: formSearch.contract_duration_days || "",
        contract_price: formSearch.contract_price || "",
      })
    },
    exportContractExcel(obj) {
      this.exportLoading = true;
      contractApi.exportContractExcel(obj).then(res => {
        console.log(res, "导出合同列表")
        this.exportLoading = false;
        if (res.code == 200) {
          this.exportUrl = res.data;
        }
        this.$message({
          type: res.code == 200 ? 'success' : 'warning',
          message: res.message
        })
      })
    },
    // 导出字段全选
    allCheckedChangeFunc(e) {
      let exportrVal = [];
      let exportArr = this.exportArr;
      if (e) {
        exportArr.forEach(item => {
          exportrVal.push(item.label);
        })
        this.exportrVal = exportrVal//已选择字段
      } else {
        this.exportrVal = exportrVal//已选择字段
      }
    },
    // 关闭导出弹窗
    exportCloseFunc() {
      this.exportArr = [];
      this.exportrVal = [];
      this.exportUrl = '';
      this.exportVisible = false;
      this.allChecked = false;
    },
    // 导出合同列表
    exportFunc() {
      switch (this.activeName) {
        case '1':
          this.exportArr = zxhtFieldArr;
          break;
        case '2':
          this.exportArr = kchtFideldArr;
          break;
        case '3':
          this.exportArr = zjxhtFideldArr;
          break;
        case '4':
          this.exportArr = djhtFideldArr;
          break;
        default:
      }
      this.exportVisible = true;
    },
    // 作废合同
    contractInvalidation() {
      this.$confirm("此操作将废弃该合同, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          contractApi
            .contractInvalidation({
              id: this.multipleSelection[0].id,
              type: this.activeName,
            })
            .then((res) => {
              console.log(res, "合同作废");
              if (res.code == 200) {
                this.onSearch();
              }
              this.$message({
                type: res.code == 200 ? "success" : "warning",
                message: res.message,
              });
            });
        })
        .catch(() => { });
    },
    // 项目列表
    selectProjectList() {
      this.projectList = [];
      commonApi.selectProjectList().then((res) => {
        console.log(res, "项目列表");
        if (res.code == 200) {
          this.searchProjectList = res.data;
        }
      });
    },
    // 品牌列表
    getBrandList() {
      brandApi
        .getBrandList({
          page: 1,
          num: 9999,
          keyword: "",
        })
        .then((res) => {
          console.log(res, "品牌列表");
          if (res.code == 200) {
            this.brandList = res.data.list;
          }
        })
        .catch(() => { });
    },
    // 门店类型列表
    getStoreTypeList() {
      storeTypeApi
        .getStoreTypeList({
          page: 1,
          num: 999,
        })
        .then((res) => {
          console.log(res, "门店类型列表");
          if (res.code == 200) {
            this.storeTypeList = res.data.list;
          }
        });
    },
    // 签约主体
    getCompanyList() {
      companyApi
        .getCompanyList({
          page: 1,
          num: 999,
          account_type: 1,
        })
        .then((res) => {
          console.log(res, "签约主体");
          if (res.code == 200) {
            this.companyList = res.data.list;
          }
        });
    },
    // 合同列表
    getContractList() {
      this.pageLoading = true;
      let formSearch = this.formSearch;
      proContractApi
        .getContractList({
          page: this.page,
          num: this.num,
          contract_type: Number(this.activeName),
          signing_company_id: formSearch.signing_company_id || "",
          project_id: formSearch.project_id || "",
          project_number: formSearch.project_number || "",
          brand_id: formSearch.brand_id || "",
          store_type_id: formSearch.store_type_id || "",
          contract_number: formSearch.contract_number || "",
          customer_contact: formSearch.customer_contact || "",
          customer_phone: formSearch.customer_phone || "",
          increase_or_decrease: formSearch.increase_or_decrease || "",
          change_content: formSearch.change_content || "",
          construction_content: formSearch.construction_content || "",
          signatory_phone: formSearch.signatory_phone || "",
          signatory_name: formSearch.signatory_name || "",
          contract_commencement_date_start: formSearch.contract_commencement_date
            ? formSearch.contract_commencement_date[0]
            : "",
          contract_commencement_date_end: formSearch.contract_commencement_date
            ? formSearch.contract_commencement_date[1]
            : "",
          contract_completion_date_start: formSearch.contract_completion_date
            ? formSearch.contract_completion_date[0]
            : "",
          contract_completion_date_end: formSearch.contract_completion_date
            ? formSearch.contract_completion_date[1]
            : "",
          contract_duration_days: formSearch.contract_duration_days || "",
          contract_price: formSearch.contract_price || "",
        })
        .then((res) => {
          console.log(res, "合同列表");
          this.pageLoading = false;
          if (res.code == 200) {
            this.tableData = res.data.list;
            this.total = res.data.max;
          } else {
            // this.$message.warning(res.message);
          }
        });
    },
    // table单行点击
    handleHighlightChangeTable(row) {
      if (!row.disabled) {
        this.$refs.table.toggleRowSelection(row);
      }
    },
    // 单页数据量修改
    handleSizeChange(e) {
      this.num = e;
      this.onSearch(1);
    },
    // 页面权限
    getHtmlAuthority() {
      commonApi
        .getHtmlAuthority({
          path: this.$route.path,
        })
        .then((res) => {
          console.log(res, "页面权限");
          if (res.code == 200) {
            this.HtmlAuthority = res.data;
          }
        });
    },
    // 搜索
    onSearch(page) {
      this.page = typeof page == "number" ? page : this.page;
      this.getContractList();
    },
    // 翻页
    handleCurrentChange(page) {
      this.onSearch(page);
    },
    moreSearchFunc() {
      this.moreSearchShow = !this.moreSearchShow;
      this.$nextTick(() => {
        this.handleResize();
      })
    },
    // 新增合同
    addContractFunc() {
      this.$store.commit('isEventTriggeredFunc', true);
      this.$router.push({
        path: "/addContract",
        query: {
          activeName: this.activeName
        }
      });
    },
    goToDetail(row) {
      this.$store.commit('isEventTriggeredFunc', true);
      this.$router.push({
        path: "/contractDetailPage",
        query: {
          id: row.id,
          type: Number(this.activeName),
        },
      });
    },
    handleSelectionChange(e) {
      console.log(e);
      this.multipleSelection = e;
    },
  },
};
</script>

<style lang="scss" scoped>
@import "./index.scss";
@import "@/styles/listPage.scss";
</style>
